<template>
  <el-button
    icon="el-icon-search"
    :loading="saving"
    type="primary"
    class="btn"
    @click="click"
  >
    扫描功能
  </el-button>
</template>

<script>
import { updateFuncs } from '@/svc/funcs'

const _getInfo = require('./_import_info_' + process.env.NODE_ENV).default
// const root = '@/views/pages'
const req = require.context('@/views/pages', true, /\.vue$/)
const requireAll = requireContext => requireContext.keys()

const re = /\.\/(.*)\.vue/

const pages = requireAll(req).map(i => {
  return i.match(re)[1]
})

export default {
  name: 'PageScanner',
  data() {
    return {
      saving: false
    }
  },
  methods: {
    click() {
      this.saving = true
      const pageList = []
      const infoEventArray = []
      for (let n = 0; n < pages.length; n++) {
        const pg = pages[n]
        infoEventArray.push(_getInfo(pg))
      }
      Promise.all(infoEventArray).then(infos => {
        let index = 0
        infos.forEach(info => {
          if (info) {
            info['file'] = pages[index]
            pageList.push(info)
          }
          index++
        })
        // console.log('1', pageList)
        updateFuncs.fn(this, pageList).then(res => {
          this.saving = false
          this.$success('成功')
          this.$emit('scanComplete')
        }).catch(() => {
          this.saving = false
        })
      })

      // for (let n = 0; n < pages.length; n++) {
      //   const pg = pages[n]
      //   // const path = `${root}/${pg}`
      //   // console.log('page', n, pg)
      //   Promise.all([_getInfo(pg)]).then(([data]) => {
      //     // const info = data['PageInfo']
      //     if (data) {
      //       console.log('data', n, data)
      //       data['file'] = pg
      //       pageList.push(data)
      //     }
      //   })
      // }
    }
  }
}
</script>
